package org.example.mallchat.adapter;

import cn.hutool.core.bean.BeanUtil;
import org.example.mallchat.domain.entity.ItemConfig;
import org.example.mallchat.domain.entity.User;
import org.example.mallchat.domain.entity.UserBackpack;
import org.example.mallchat.domain.vo.response.UserBadgeRep;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: zzh
 * @date: 2024/12/23 17:40:21
 * @version: 1.0
 */
public class ResultVoBuilder {
    public static List<UserBadgeRep> buildUserBadgeList(List<ItemConfig> itemConfigListByType, List<UserBackpack> userBackpackList,
                                                        User user) {
        // 用户拥有的徽章id列表
        Set<Long> userObtainItemIdSet = userBackpackList.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        // 封装用户拥有的徽章列表以及没有拥有的徽章列表 以及要进行排序， 已拥有的徽章在前，未拥有的徽章在后，佩戴的在最前面！
        return itemConfigListByType.stream().map(itemConfig -> {
            UserBadgeRep userBadgeRep = BeanUtil.copyProperties(itemConfig, UserBadgeRep.class);
            userBadgeRep.setHas(userObtainItemIdSet.contains(itemConfig.getId()));
            userBadgeRep.setWearing(itemConfig.getId().equals(user.getItemId()));
            return userBadgeRep;
        }).sorted((userBadgeRep1, userBadgeRep2) -> {
            // 先按 wearing 排序 ，佩戴的在最前面
            int hasCompare = Boolean.compare(userBadgeRep2.getWearing(), userBadgeRep1.getWearing());
            if (hasCompare != 0) {
                return hasCompare;
            }
            // 如果 wearing 相同，再按 has 排序
            return Boolean.compare(userBadgeRep1.getHas(), userBadgeRep2.getHas());
        }).collect(Collectors.toList());
    }
}
